export const imgDownload = (url: string, name: string = 'download') => {
  if (!url) return
  const imgUrl = url
  // 图片格式为base64
  const nav = window.navigator as any
  if (nav.msSaveOrOpenBlob) {
    const bstr = atob(imgUrl.split(',')[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    const blob = new Blob([u8arr])
    nav.msSaveOrOpenBlob(blob, name)
  } else {
    // 这里就按照chrome等新版浏览器来处理
    const a = document.createElement('a')
    a.href = imgUrl
    a.setAttribute('download', name)
    a.click()
  }
  // 方案二
  // let image = new Image()
  // image.setAttribute('crossOrigin', 'anonymous')
  // image.onload = function () {
  //   let canvas = document.createElement('canvas')
  //   canvas.width = image.width
  //   canvas.height = image.height
  //   let context: any = canvas.getContext('2d')
  //   context.drawImage(image, 0, 0, image.width, image.height)
  //   let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
  //   let a = document.createElement('a') // 生成一个a元素
  //   let event = new MouseEvent('click') // 创建一个单击事件
  //   a.download = 'photo' // 设置图片名称
  //   a.href = url // 将生成的URL设置为a.href属性
  //   a.dispatchEvent(event) // 触发a的单击事件
  // }
  // image.src = imgUrl
  // return Promise.resolve()
  // 方案三
  // let x = new XMLHttpRequest()
  // x.open('GET', imgUrl, true)
  // x.responseType = 'blob'
  // x.onload = function () {
  //   let url = window.URL.createObjectURL(x.response)
  //   let a = document.createElement('a')
  //   a.href = url
  //   a.download = 'chart-download'
  //   a.click()
  // }
  // x.send()
}
